import React, {useEffect, useState} from 'react';
import List from "@material-ui/core/List";
import ListItemText from "@material-ui/core/ListItemText";
import Typography from "@material-ui/core/Typography";
import ListItem from "@material-ui/core/ListItem";
import makeStyles from "@material-ui/core/styles/makeStyles";
import axios from "axios";
import {useHistory, useLocation} from 'react-router-dom'
import {BASE_URL, SERVER_ERROR_MESSAGE} from "../constants";
import Link from '@material-ui/core/Link';
import InlineError from "./InlineError";
import LoadingSpinner from "./LoadingSpinner";

const useStyles = makeStyles(theme => ({
    links: {
        fontSize: "1.2em",
        fontWeight: 800,
        paddingLeft: theme.spacing(2),
        marginTop: theme.spacing(4),
        marginBottom: theme.spacing(2),
    },
    active: {
        background: "#f1f1f1",
    }
}))

export default function Sidenav() {
    const classes = useStyles()
    const history = useHistory()
    const location = useLocation()

    const [state, setState] = useState({
        categories: [],
        links: [],
        loading: true,
        error: ''
    })

    async function fetchCategories(url) {
        try {
            const response = await axios.get(url)
            const data = await response.data
            setState(prevState => ({...prevState, loading: false, categories: data, error: ''}))
        } catch (err) {
            setState(prevState => ({...prevState, loading: false, categories: [], error: SERVER_ERROR_MESSAGE}))
        }
    }

    async function fetchLinks(url) {
        try {
            const response = await axios.get(url)
            const data = await response.data
            setState(prevState => ({...prevState, loading: false, links: data, error: ''}))
        } catch (err) {
            setState(prevState => ({...prevState, loading: false, links: [], error: SERVER_ERROR_MESSAGE}))
        }
    }

    useEffect(() => {
        fetchCategories(`${BASE_URL}/categories/`)
        fetchLinks(`${BASE_URL}/links/`)
    }, [])

    const navLinks = [
        {path: '/most_recent', text: '最近推荐'},
        {path: '/month_most_viewed', text: '本月排行'},
        {path: '/most_viewed', text: '历史排行'},
    ]

    const {categories, links, loading, error} = state

    if (loading) return <LoadingSpinner/>
    if (error) return <InlineError error={error}/>

    return (
        <List component="nav">
            {navLinks.map(link => (
                <ListItem
                    button
                    key={link.text}
                    onClick={() => history.push(link.path)}
                    className={location.pathname === link.path ? classes.active : null}
                >
                    <ListItemText primary={link.text}/>
                </ListItem>
            ))}

            <Typography variant="h6" className={classes.links}>分类阅读</Typography>
            {/*不空时才执行map*/}
            {!!categories && categories.map(category => (
                <ListItem
                    button
                    key={category.name}
                    onClick={() => history.push(`/${category.name}/books/`)}
                    className={location.pathname === `/${category.name}/books/` ? classes.active : null}
                >
                    <ListItemText primary={category.name}/>
                </ListItem>
            ))}

            <Typography variant="h6" className={classes.links}>推荐链接</Typography>

            {!!links && links.map(link => (
                <Link href={link.url} color="inherit" key={link.name}>
                    <ListItem button>
                        <ListItemText>
                            {link.name}
                        </ListItemText>
                    </ListItem>
                </Link>
            ))}
        </List>
    );
};

